﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using cecbData;
using System.Collections.ObjectModel;
using cecbClasses.Data_Adapters;
using System.Text.RegularExpressions;
using cecbClasses.Data_Adapters.Project;

namespace CECB
{
    /// <summary>
    /// Interaction logic for V_FillMatrix_Window.xaml
    /// </summary>
    public partial class V_FillMatrix_Window : Window
    {

       private DSSEntities dataContext;
       private Boolean isProjectSelected = false;
       private Boolean isLeopoldProject = false;
       private Projects proj;
       private String ProjId = "";
       private String _activityRef = null;
       private String _impactRef = null;
       private String projectMatrixType = null;
     
        public V_FillMatrix_Window()
        {
            InitializeComponent();
            dataContext = new DSSEntities();
            ProjectAutocompleteTextBox.IsEnabled = false;
            ProjectAutocompleteTextBox.ItemsSource = new Func_Projects().getAllProjects();
            buttonAddMatrix.IsEnabled = false;
            groupBoxinsertValues.IsEnabled = false;
            textBoxImportance.Text = 0+"";
            textBoxMagnitude.Text = 0+"";

        }


       

        private TreeViewItem SetTreeViewActivity(string text, string magVal, String impVal, String displyVal, Boolean valueType , Boolean projType)
        {

            bool isWithValues = valueType;
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;


            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;
            stack.Children.Add(lbl);
            if (isWithValues)
            {
                if (projType)
                {
                    Label lbl1 = new Label();
                    lbl1.Content = "" + magVal + "" + impVal + "";
                    lbl1.Foreground = Brushes.Green;
                    stack.Children.Add(lbl1);
                }
                else {

                    Label lbl1 = new Label();
                    lbl1.Content = "  " + impVal + "";
                    lbl1.Foreground = Brushes.Green;
                    stack.Children.Add(lbl1);
                }

            }

            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }


        private TreeViewItem SetTreeViewImpacts(string text, String displyVal)
        {
            TreeViewItem item = new TreeViewItem();

            item.IsExpanded = true;

            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;


            Label lbl = new Label();
            lbl.Name = "lblImpText";
            lbl.Content = text;

            stack.Children.Add(lbl);


            item.Header = stack;

            item.Foreground = Brushes.Brown;
            item.BorderBrush = Brushes.Black;
            item.FontStyle = FontStyles.Italic;
            item.Cursor = Cursors.Hand;
            item.FontSize = 13;
            item.Height = 22;
            item.DisplayMemberPath = displyVal;


            return item;
        }
         

        #region Fill Impacts

        public void fillImpacts()
        {
            
            IQueryable<Components> qComponents = (from c in dataContext.ProjectImpacts
                                                  join b in dataContext.Impacts on c.impt_reference equals b.impt_reference
                                                  join d in dataContext.Components on b.impt_component equals d.cmpt_reference
                                                  where c.proj_reference == ProjId
                                                  orderby b.impt_component
                                                  select d).Distinct();

            int y = 0;
            foreach (Components com in qComponents)
            {

                treeView1.Items.Add(new TreeViewItem() { Header = com.cmpt_name //,
                                                      //   FontStyle = FontStyles.Italic,
                                                       //  FontWeight = FontWeights.Bold 
                });
                
                IQueryable<Impacts> qImpacts = from c in dataContext.ProjectImpacts
                                               join b in dataContext.Impacts on c.impt_reference equals b.impt_reference

                                               where c.proj_reference == ProjId && b.impt_component == com.cmpt_reference
                                               orderby b.impt_component
                                               select b;
                
               
                foreach (Impacts imp in qImpacts)
                { 
                    ((TreeViewItem)treeView1.Items[y]).Items.Add(SetTreeViewImpacts(imp.impt_name.ToString(), imp.impt_reference.ToString()));
                    ((TreeViewItem)treeView1.Items[y]).IsExpanded = true;
                }
                y++;

            }
        }

        #endregion

        #region Fill Activity

        public void fillActivities(String impRef, String projRef, Boolean isWithValue , Boolean projType)
        {

            //-------------------------------------------------------------------------------

            IQueryable<Activities> qActivities = (from c in dataContext.ProjectActivities
                                                  join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == projRef
                                                  orderby b.actv_phase
                                                  select b).GroupBy(b => b.actv_phase).Select(x => x.FirstOrDefault());

            int y = 0;
            foreach (Activities act in qActivities)
            {

                treeView2.Items.Add(new TreeViewItem() { Header = act.actv_phase//,
                                                        // FontStyle = FontStyles.Italic,
                                                        // FontWeight = FontWeights.Bold
                                                        });

                IQueryable<Activities> qImpacts = from c in dataContext.ProjectActivities
                                                  join b in dataContext.Activities on c.actv_reference equals b.actv_reference

                                                  where c.proj_reference == projRef && b.actv_phase == act.actv_phase
                                                  select b;

                foreach (Activities imp in qImpacts)
                {

                    if (isWithValue)
                    {
                        String impID = impRef;
                        String projID = projRef;
                        String actvID = imp.actv_reference.ToString();
                        if (projType)
                        { 
                            String impVal = getLeopoldImportenceValue(projRef, impID, actvID);
                            String magVal = getLeopoldMagnitudeValue(projRef, impID, actvID);

                            ((TreeViewItem)treeView2.Items[y]).Items.Add(SetTreeViewActivity(imp.actv_name.ToString(), magVal, impVal, imp.actv_reference.ToString(), true , true));
                        }
                        else
                        { 
                            String impVal = getSimpleMagnitudeValue(projRef, impID);
                            ((TreeViewItem)treeView2.Items[y]).Items.Add(SetTreeViewActivity(imp.actv_name.ToString(), "", impVal, imp.actv_reference.ToString(), true, false));
                        }
                    }
                    else
                        ((TreeViewItem)treeView2.Items[y]).Items.Add(SetTreeViewActivity(imp.actv_name.ToString(), "", "", imp.actv_reference.ToString(), false, isLeopoldProject));
                        ((TreeViewItem)treeView2.Items[y]).IsExpanded = true;
                }
                y++;
            }

        }

        private String getLeopoldImportenceValue(String projID, String impRef, String actRef)
        {

            try
            {
                var quary = from c in dataContext.LeopoldMatrixValues
                            where c.proj_reference == projID &&
                                    c.actv_reference == actRef &&
                                    c.impt_reference == impRef

                            select c.mtrx_importance.Value;

                return " / Imp:  " + quary.First().ToString() + " )";
            }
            catch (InvalidOperationException)
            {
                //return "Not Assigned";
                return "";
            }
        }

        private String getLeopoldMagnitudeValue(String projID, String impRef, String actRef)
        {

            try
            {
                var quary = from c in dataContext.LeopoldMatrixValues
                            where c.proj_reference == projID &&
                                    c.actv_reference == actRef &&
                                    c.impt_reference == impRef

                            select c.mtrx_magnitude.Value;

                return "( Mag: " + quary.First().ToString();
            }
            catch (InvalidOperationException)
            {
               // return "Not Assigned";
                return "";
            }
        }


        private String getSimpleMagnitudeValue(String projID, String impRef )
        {

            try
            {
                var quary = from c in dataContext.SimpleMatrixValues
                            where c.proj_reference == projID &&
                                     
                                    c.impt_reference == impRef

                            select c.mtrx_value.Value;

                return quary.First().ToString();
            }
            catch (InvalidOperationException)
            {
                return "Not Assigned";
            }
        }
         
        #endregion

        public bool IsDataAvailabel(String imp, String act, String pid)
        {
            bool ok = false;

            var quary = from c in dataContext.LeopoldMatrixValues
                        where c.proj_reference == pid &&
                                c.actv_reference == act &&
                                c.impt_reference == imp &&
                                c.mtrx_magnitude.HasValue &&
                                c.mtrx_importance.HasValue
                        select c;

            if (quary.ToList().Count > 0)
                ok = true;

            return ok;
        }

        public void clearTreeBackGround(TreeView tvi)
        {

            try
            {
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[0]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[1]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
                foreach (TreeViewItem x in ((TreeViewItem)tvi.Items[2]).Items)
                {
                    x.Background = Brushes.Transparent;
                }
            }
            catch (Exception)
            {


            }
        }

        private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                refreshTreeViewActivitiesData(isLeopoldProject);
                textBoxImportance.Text = 0 + "";
                textBoxMagnitude.Text = 0 + "";
            }
            catch (Exception)
            {

            }
        }

        private void refreshTreeViewActivitiesData( Boolean projType) {
            this.Cursor = Cursors.Wait;
            TreeViewItem tvi = (TreeViewItem)treeView1.SelectedItem;
            StackPanel stp = (StackPanel)tvi.Header;
            Label lblText = (Label)stp.Children.OfType<Label>().First();

            labelImpact.Content = lblText.Content.ToString();

            _impactRef = tvi.DisplayMemberPath.ToString();
             treeView2.Items.Clear();
            
            fillActivities(_impactRef, ProjId, true , projType);           
            this.Cursor = Cursors.Arrow;
        }

        private void treeView2_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {

                buttonConfirm.IsEnabled = true;
                buttonAddMatrix.IsEnabled = false;

                TreeViewItem tvi = (TreeViewItem)treeView2.SelectedItem;
                StackPanel stp = (StackPanel)tvi.Header;
                Label lblText = (Label)stp.Children.OfType<Label>().First();
                labelActivity.Content = lblText.Content.ToString();
                _activityRef = tvi.DisplayMemberPath.ToString();
                textBoxImportance.Text = 0 + "";
                textBoxMagnitude.Text = 0 + "";

            }
            catch (Exception)
            {
                 
            }

            //if (IsDataAvailabel(_impactRef, _activityRef, ProjId)) {
            //    tvi.Background = Brushes.Green;

            //}

        }


        private void ProjectTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (((AutoCompleteBox)sender).SelectedItem != null)
            {
               
                try
                {

                    treeView1.Items.Clear();
                    treeView2.Items.Clear();
                    textBoxImportance.Text = 0 + "";
                    textBoxMagnitude.Text = 0 + "";

                    if (ComboboxSelectMatrix.SelectedIndex > -1)
                    {
                        isProjectSelected = true;
                        groupBoxinsertValues.IsEnabled = true;
                        proj = (Projects)((AutoCompleteBox)sender).SelectedItem;
                        ProjId = proj.proj_reference;

                        fillImpacts();
                        fillActivities("", ProjId, false, isLeopoldProject);

                        if (ComboboxSelectMatrix.SelectedIndex == 1)
                        {
                           

                            try
                            {
                                var range = (from c in dataContext.ProjectCriteria
                                             where c.proj_reference == ProjId &&
                                                    c.proj_matrix == "Leopold"
                                             select c.crt_range).FirstOrDefault();

                                // foreach (var x in range)
                                // {
                              //  Iv.Content = range.ToString();
                             //   Mv.Content = range.ToString();

                                //  }
                            }
                            catch (Exception)
                            {


                            }
                        }
                        else
                        {

                            //try
                            //{
                            //     var range = (from c in dataContext.ProjectCriteria
                            //             where c.proj_reference == ProjId &&
                            //                    c.proj_matrix == "Simple"
                            //             select c.crt_range).FirstOrDefault();

                            //foreach (var x in range)
                            //{
                            //    Iv.Content = x.ToString();
                            //}
                            //}
                            //catch (Exception)
                            //{


                            //}

                        }

                    }
                    else
                    {
                        // ProjectAutocompleteTextBox.SelectedItem = null;

                        MessageBox.Show("Select a matrix type!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                catch (Exception)
                {
                    // MessageBox.Show("System Error!", "Message", MessageBoxButton.OK, MessageBoxImage.Error);

                }
            }
            else {
                treeView1.Items.Clear();
                treeView2.Items.Clear();
                isProjectSelected = false;
                buttonAddMatrix.IsEnabled = false;
                buttonConfirm.IsEnabled = false;
                textBoxImportance.Clear();
                textBoxImportance.IsReadOnly = true;
                textBoxMagnitude.Clear();
                textBoxMagnitude.IsReadOnly = true;
                groupBoxinsertValues.IsEnabled = false;
            }
        }

        private void buttonConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (isProjectSelected)
            {
                if (labelImpact.Content.ToString() == "")
                {
                    MessageBox.Show("Select an impact to add value", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else if (labelActivity.Content.ToString() == "")
                {
                    MessageBox.Show("Select an activity to add value", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    buttonAddMatrix.IsEnabled = true;
                    stackPanelActivity.Background = new SolidColorBrush(Colors.Green);
                    stackPanelImpact.Background = new SolidColorBrush(Colors.Green);
                    textBoxImportance.IsEnabled = true;
                    textBoxMagnitude.IsEnabled = true;
                }
            }
            else
                MessageBox.Show("Select a project ", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void textBoxMagnitude_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void textBoxMagnitude_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        private void textBoxImportance_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9]+");
            e.Handled = regex.IsMatch(e.Text);
        }



        private void buttonAddMatrix_Click(object sender, RoutedEventArgs e)
        {
            String impName = labelImpact.Content.ToString();
            String actName = labelActivity.Content.ToString();
            String ival = textBoxMagnitude.Text.ToString();
            String mval = textBoxImportance.Text.ToString();

            if (labelImpact.Content.ToString() == "")
            {
                MessageBox.Show("Enter impact name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else if (labelActivity.Content.ToString() == "")
            {
                MessageBox.Show("Enter activity name", "Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            else if (true)
            {
                if (ComboboxSelectMatrix.SelectedIndex == 1)
                {

                    cecbClasses.Data_Adapters.Func_FillMatrix fillmx = new cecbClasses.Data_Adapters.Func_FillMatrix();
                    if (fillmx.InsertValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text))
                    {
                        MessageBox.Show("Inserted Leopold Matrix Value", "Message", MessageBoxButton.OK, MessageBoxImage.Information);

                        buttonConfirm.IsEnabled = false;
                    }
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Values are already in database! Do you want to update?", "Message", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            // fillmx.UpdateValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text);
                        }

                    }
                }

                else if (ComboboxSelectMatrix.SelectedIndex == 0)
                {


                    if (new cecbClasses.Data_Adapters.MatrixSimple.SimpleMatrixCalculation().InsertValuesToSimpleMatrix(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxImportance.Text))
                    {
                        MessageBox.Show("Inserted Simple Matrix Value", "Message", MessageBoxButton.OK, MessageBoxImage.Information);

                        buttonConfirm.IsEnabled = false;
                    }
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Values are already in database! Do you want to update?", "Message", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == MessageBoxResult.Yes)
                        {
                            // fillmx.UpdateValues(_impactRef, _activityRef, proj.proj_reference.ToString(), textBoxMagnitude.Text, textBoxImportance.Text);
                        }

                    }

                }
                refreshTreeViewActivitiesData(isLeopoldProject);
                textBoxImportance.Text = "";
                textBoxMagnitude.Text = "";
                textBoxImportance.IsEnabled = false;
                textBoxMagnitude.IsEnabled = false;
                stackPanelActivity.Background = new SolidColorBrush(Colors.Red);
                stackPanelImpact.Background = new SolidColorBrush(Colors.Red);

            }




        }

        private void textBoxMagnitude_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void ProjectAutocompleteTextBox_TextChanged(object sender, RoutedEventArgs e)
        {
            isProjectSelected = false;

        }

        private void ComboboxSelectMatrix_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ComboboxSelectMatrix.SelectedIndex == 0)
            {
                isLeopoldProject = false;
                lblimp.Visibility = System.Windows.Visibility.Hidden;
                lblmag.Visibility = System.Windows.Visibility.Visible;
                textBoxMagnitude.Visibility = System.Windows.Visibility.Hidden;
                lblmag.Content = "Importance Value";

            }
            else if (ComboboxSelectMatrix.SelectedIndex == 1)
            {
                isLeopoldProject = true;
                lblimp.Visibility = System.Windows.Visibility.Visible;
                lblmag.Visibility = System.Windows.Visibility.Visible;
                textBoxImportance.Visibility = System.Windows.Visibility.Visible;
                textBoxMagnitude.Visibility = System.Windows.Visibility.Visible;
                lblmag.Content = "Magnitude Value";
            }

            ProjectAutocompleteTextBox.IsEnabled = true;
        }

        private void textBoxMagnitude_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void btnMagplus_Click(object sender, RoutedEventArgs e)
        {
            int x = Int32.Parse(( textBoxMagnitude.Text.ToString()));
            x += 1;
            textBoxMagnitude.Text = x.ToString(); 

        }

        private void btnMagminus_Click(object sender, RoutedEventArgs e)
        {
            int x = Int32.Parse( textBoxMagnitude.Text.ToString());
            x -= 1;
            textBoxMagnitude.Text = x.ToString(); 
        }

        private void btnImpplus_Click(object sender, RoutedEventArgs e)
        {
            int x = Int32.Parse(textBoxImportance.Text.ToString());
            x += 1;
            textBoxImportance.Text = x.ToString(); 
        }

        private void btnimpminus_Click(object sender, RoutedEventArgs e)
        {
            int x = Int32.Parse((textBoxImportance.Text.ToString()));
            x -= 1;
            textBoxImportance.Text = x.ToString(); 
        }



    }

}
